package dao.impl;

import javax.naming.NamingException;

import org.eclipse.jdt.annotation.NonNull;

import bean.Account;
import dao.AccountDAO;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class AccountDAOImpl implements AccountDAO {
    private Connection conn;
    
    public AccountDAOImpl(@NonNull Connection conn) {
        this.conn = conn;
    }

    @Override
    public int selectIdByAccount(@NonNull Account temporary) throws NamingException, SQLException {
        String sql = "SELECT ACCOUNT_ID FROM ACCOUNTS WHERE ACCOUNT_NAME=? AND PASSWORD=?";
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setString(1, temporary.getAccountName());
        ps.setString(2, temporary.getPassword());
        int accountId;
        ResultSet rs = ps.executeQuery();
        if (rs.next()) {
            accountId = rs.getInt("ACCOUNT_ID");
        } else {
            accountId = 0;
        }
        rs.close();
        ps.close();
        return accountId;
    }

    @Override
    public boolean insert(@NonNull Account temporary) throws SQLException, NamingException {
        String sql = "INSERT INTO ACCOUNTS VALUES(NULL,?,?)";
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setString(1, temporary.getAccountName());
        ps.setString(2, temporary.getPassword());
        ps.executeUpdate();
        ps.close();
        return true;
    }

    @Override
    public boolean update(@NonNull Account temporary, @NonNull String newPassword) throws SQLException, NamingException {
        if (temporary.getAccountId() != selectIdByAccount(temporary)) {
            return false;
        }
        String sql = "UPDATE ACCOUNTS SET PASSWORD=? WHERE ACCOUNT_ID=?";
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setString(1, newPassword);
        ps.setInt(2, temporary.getAccountId());
        boolean state = ps.executeUpdate() == 1;
        ps.close();
        return state;
    }
}
